<script setup lang="ts">
import {Camera, Delete, VideoPlay} from '@element-plus/icons-vue'
import {ContextMenu, ContextMenuItem} from '@imengyu/vue3-context-menu'

import {accessRecordsDB, movieDB} from '@/data/lowdb.ts'
import {videoImagesDir} from '@/utils/config.ts'
import {recordVideoAccessRecords} from '@/data/access_records.ts'
import {AccessRecord, Movie} from '@/data/Dream'
import {ref, inject, Ref} from 'vue'
import {ElMessage} from 'element-plus'
import {calVideoPath, openVideoDefault} from '@/utils/utils.ts'

const props = defineProps<{
  videoAccessRecords: Map<string, AccessRecord> | undefined
}>()

const movie = inject<Ref<Movie>>('movie', ref())

// 视频文件名
let videoFile: string
// 图片文件名
let videoImage: string

const videoImages = ref<string[]>([])
const videoImageIndex = ref(0)

let exec: any
({exec} = require('child_process'));
const portPlayer = `D:/PotPlayer/PotPlayerMini64.exe`

function playSeek() {
  let fileFullPath = calVideoPath(movie.value, videoFile)
  fileFullPath = fileFullPath.replaceAll('/', '\\')

  // 2017.少年锦衣卫.第2季.03[夜市]-00.09.38.498-00.12.35.095-seg2.mp4_000218.989.jpg
  let seekTime = videoImage.match(/_(\d{6})\.\d{3}\.jpg/)
  seekTime = seekTime[1].match(/(\d{2})(\d{2})(\d{2})/)
  let seekTimeFormat = `${seekTime[1]}:${seekTime[2]}:${seekTime[3]}`

  const cmd = `${portPlayer} ${fileFullPath} /seek=${seekTimeFormat}`
  console.log(cmd)
  exec(cmd)
  props.videoAccessRecords.set(videoFile, recordVideoAccessRecords(videoFile))
}

let fs: any
fs = require('fs')

import _ from 'lodash'

function deleteImgFile() {
    if (videoImages.value.length === 1) {
        const fileFullPath = calVideoPath(movie.value, videoFile)
        fs.unlinkSync(fileFullPath)
        console.log('video file remove: ', fileFullPath)
        // 只剩下一张图片时，把视频文件也删除
        _.remove(movie.value.dreamVideos, {video: videoFile})
        console.log('video data remove: ', videoImageIndex.value)
        // 删除视频的观看记录
        const records = accessRecordsDB.get('videoAccessRecords').value()
        if (records[videoFile]) {
            delete records[videoFile]
            accessRecordsDB.write()
        }
        props.videoAccessRecords.delete(videoFile)
    } else {
        videoImages.value.splice(videoImageIndex.value, 1)
        console.log('image data remove: ', videoImageIndex.value)
    }
    movieDB.write()

    const removeImageFile = videoImagesDir + videoImage
    fs.unlinkSync(removeImageFile)
    console.log('image file remove: ', removeImageFile)

    ElMessage({message: `${videoImage} 删除成功`, type: 'success'})
}

const menuVisibility = ref(false)

const optionsComponent = ref({
  theme: 'flat', zIndex: 3, minWidth: 1, x: 500, y: 200,
})

//显示组件菜单
function showContextMenu(e: MouseEvent) {
  menuVisibility.value = true
  optionsComponent.value.x = e.x
  optionsComponent.value.y = e.y
}

let longPressTimeout = null

function handleMouseDown(e: MouseEvent, video: string, img: string) {
    if (e.button !== 2) return
    videoFile = video
    videoImage = img

    videoImages.value = movie.value
        .dreamVideos
        .find(v => v.video === videoFile)
        .images
    videoImageIndex.value = videoImages.value
        .findIndex(image => image === videoImage)

    longPressTimeout = setTimeout(() => {
        showContextMenu(e)
    }, 500)
}

function handleMouseUp(e: MouseEvent) {
    if (e.button !== 2) return
    clearTimeout(longPressTimeout)
    if (!menuVisibility.value) {
        openVideoDefault(movie.value, videoFile, props.videoAccessRecords)
    }
}

// 设置图片到电影封面
function setToMovieCover() {
    const m = movie.value
    if (m.images.length === 3) {
        m.images.pop()
    }
    m.images.unshift(videoImage)

    movieDB.write()
    ElMessage({message: `设置图片到电影封面：${videoImage}`, type: 'success'})
}

// 把图片设置为视频封面
function setToVideoCover() {
    const newCover = videoImages.value[videoImageIndex.value]
    const oldCover = videoImages.value[0]
    videoImages.value[0] = newCover
    // 从新 cover 的 index 处开始寻找旧 cover 在数组中插入位置
    let insertIndex = videoImageIndex.value
    if (oldCover < newCover) {
        // 和一个比较
        while (insertIndex > 1 && oldCover < videoImages.value[insertIndex - 1]) {
            videoImages.value[insertIndex] = videoImages.value[insertIndex - 1]
            insertIndex--
        }
    } else {
        // 和后个比较
        while (insertIndex < videoImages.value.length - 1 &&
            oldCover > videoImages.value[insertIndex + 1])
        {
            videoImages.value[insertIndex] = videoImages.value[insertIndex + 1]
            insertIndex++
        }
    }
    videoImages.value[insertIndex] = oldCover
    console.log(`第 ${videoImageIndex.value} 个图片设置为新封面，旧封面回到数组原来的第 ${insertIndex} 个位置`)
    movieDB.write()
}

defineExpose({
  handleMouseDown, handleMouseUp,
})
</script>

<template>
  <context-menu
      v-model:show="menuVisibility"
      :options="optionsComponent">
    <context-menu-item label="play" @click="playSeek">
      <template #icon>
        <el-icon color="blue">
          <VideoPlay/>
        </el-icon>
      </template>
    </context-menu-item>
    <context-menu-sperator/>
    <template v-if="videoImageIndex > 0">
      <context-menu-item label="video cover" @click="setToVideoCover">
        <template #icon>
          <el-icon>
            <!--suppress HtmlUnknownAttribute -->
            <Picture color="purple"/>
          </el-icon>
        </template>
      </context-menu-item>
      <context-menu-sperator/>
    </template>
    <context-menu-item label="movie cover" @click="setToMovieCover">
      <template #icon>
        <el-icon>
          <Camera color="green"/>
        </el-icon>
      </template>
    </context-menu-item>

    <context-menu-sperator/>
    <context-menu-item label="delete" @click="deleteImgFile">
      <template #icon>
        <el-icon color="red">
          <Delete/>
        </el-icon>
      </template>
    </context-menu-item>
  </context-menu>
</template>
